﻿namespace Beetle
{
    using System;
    using System.Text;

    public class ObjectFormatter
    {
        private static BufferWriter _field_a;
        private static BufferReader _field_b;
        private static object _field_c = new object();
        private static object _field_d = new object();
        public static int EncodingStringMaxLength = 0x200;

        public static T Deserialize<T>(ByteArraySegment segment) where T: IMessage, new()
        {
            return Deserialize<T>(segment, Encoding.UTF8);
        }

        public static T Deserialize<T>(ByteArraySegment segment, Encoding coding) where T: IMessage, new()
        {
            return (T) Deserialize(typeof(T), segment, coding);
        }

        public static void Deserialize(IMessage msg, ByteArraySegment segment)
        {
            Deserialize(msg, segment, Encoding.UTF8);
        }

        public static void Deserialize(IMessage msg, ByteArraySegment segment, Encoding coding)
        {
            lock (_field_d)
            {
                if (_field_b == null)
                {
                    _field_b = new BufferReader(coding);
                }
                _field_b.Coding = coding;
                _field_b.CleanBuffer();
                _field_b.Import(segment);
                msg.Load(_field_b);
            }
        }

        public static IMessage Deserialize(Type type, ByteArraySegment segment, Encoding coding)
        {
            lock (_field_d)
            {
                if (_field_b == null)
                {
                    _field_b = new BufferReader(coding);
                }
                _field_b.Coding = coding;
                _field_b.CleanBuffer();
                _field_b.Import(segment);
                IMessage message = (IMessage) Activator.CreateInstance(type);
                message.Load(_field_b);
                return message;
            }
        }

        public static void Serialize(IMessage message, ByteArraySegment segment)
        {
            Serialize(message, segment, Encoding.UTF8);
        }

        public static void Serialize(IMessage message, ByteArraySegment segment, Encoding coding)
        {
            lock (_field_c)
            {
                if (_field_a == null)
                {
                    _field_a = new BufferWriter(coding, true);
                }
                _field_a.Coding = coding;
                _field_a.Reset();
                message.Save(_field_a);
                segment.Import(_field_a);
            }
        }

        public static void Setup()
        {
            TcpUtils.StringEncodingLength = EncodingStringMaxLength;
            TcpUtils.Setup(100, 1, 0);
        }
    }
}

